<?php
namespace App\Controllers\Order;
use App\Models\Goods\Goods;
use App\Models\Order\Order;
use App\Models\Goods\GoodsAffiliate;
use App\Models\Store\Store;
use App\Libs\Order\OrderList;

/**
*	获取订单
*/
class GetOrder extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }
	
	public function execute(){
		$user = $this->session->user;
		//获取信息
		$orderSn = $this->request->get('orderSn');//订单号
		$type = $this->request->get('type');//获取类型
		$lat = $this->request->get('lat');//维度
		$lnt = $this->request->get('lnt');//经度
		$page = (int)$this->request->get('page');//获取类型
		$size = (int)$this->request->get('size');//获取类型
		$status = $this->request->get('status');//订单状态
		
		if( $type == 'det' && !empty( $orderSn ) ){
			//订单信息
			$order = Order::find( array(
				'order_sn = :orderSn: and uid = '.$user->id,
				'bind'=>array( 'orderSn' => $orderSn )
			) );
			if( empty( $order ) ){
				return \App\Libs\Views\Json::view(1, '未查找到相关订单', Null );
			}
			
			//商品信息
			$goods = Goods::find( array(
				' id = :gid:',
				'bind'=>array( 'gid' => $order->gid )
			) );
			if( empty( $goods ) ){
				return \App\Libs\Views\Json::view(1, '未查找到订单相关商品信息', Null );
			}
			
			//商品附属信息
			$affiliate = GoodsAffiliate::find(array(
				'gid = :gid:',
				'bind' => array('gid'=>$goods->id),
			));
			
			//店铺信息
			$store = Store::find(array(
				'id = :sid:',
				'bind' => array('sid'=>$goods->sid),
			))->toArray();
			$store['distance'] = \App\Libs\Helper\CommonHelper::getDistance( $lat , $lnt , $store['latitude'] , $store['longitude'] );
			
			return \App\Libs\Views\Json::view(0, '成功', ['info'=>$order,'store'=>$store,'affiliate'=>$affiliate,'goods'=>$goods]);
			
		}
		if( $type == 'list' ){
			//订单列表
			if(  empty( $page ) ){
				$page = 1;
			}
			if( empty( $size ) ){
				$size = 10;
			}
			
			/*$offset = ($page-1)*$size;
			
			//订单信息
			$order = Order::findAll( array(
				'uid = '.$user->id,
				'offset' => $offset,
				'limit' => $size,
			) )->toArray();*/
			//订单相关信息
			$order = OrderList::OrderList( $user , ['page'=>$page,'size'=>$size,'status'=>$status]);
			
			if( empty( $order ) ){
				return \App\Libs\Views\Json::view(0, '未查找到相关订单', [] );
			}else{
				$nowTime = date("Y-m-d H:i:s");
				foreach( $order as $k=>$v ){
					if( $v['stime'] < $nowTime && $v['status'] == 0 ){
						$order[$k]['status'] = '已失效';
						continue;
					}
					$order[$k]['status'] = \App\Libs\Base\Config::instance()->common['goodsFlag'][$v['status']];
				}
				return \App\Libs\Views\Json::view(0, '成功', $order );
			}
			
		}
		return \App\Libs\Views\Json::view(1, '传递参数有误，请检查参数', Null );
	}
}
